﻿#include"include\Interfaces\BinocularCamera.h"
#include <opencv2/videoio.hpp>
#include<QDateTime>
#include <QDebug>



BinocularCamera::BinocularCamera(USBPort id)
	:_port(SettingDialog::getCameraDevices().getCamID(id))				//CameraID(USBPort id)
{	
}

BinocularCamera::~BinocularCamera() {
	qDebug() << "Decon	struct BinocularCamera>>>>>>>>>>>>>>>>>>>>>>>>>";
	close();
}

void BinocularCamera::open() {		//打开相机

	qDebug() << "BinocularCamera::open";
	_cam = std::make_shared<CameraInfo>();			//返回一个shared_ptr，指向值初始化的CameraIofo的对象，并且初始化
	_cam->id = _port;
	_cam->errorCode = DEV_ERR_IRI_SCAM_NOTOPEN;   //-1
	_cam->errorMsg = "虹膜相机无法连接！";

	_cam->vc = new cv::VideoCapture(_port/*+cv::CAP_MSMF*/);		//vc来连接摄像头_id=0，1

	_cam->vc->set(cv::CAP_PROP_SATURATION, 0);	

	_isCameraInitialize = _cam->vc->isOpened();

}

void BinocularCamera::setParam(int type, double value)
{
	_cam->vc->set(type,value);
}

double BinocularCamera::getParam(int type)
{
	return _cam->vc->get(type);

}

void BinocularCamera::close() {
	if (_isCameraInitialize) {
		_cam.reset();												//引用计数减1
		_isCameraInitialize = false;
	}
}

BinocularCamera::CameraInfo::~CameraInfo() {
	if (nullptr != vc)
		delete vc;
}

bool BinocularCamera::CameraInfo::isCameraConnected() {
	if (nullptr == vc) {
		return false;
	}
	cv::Mat img;
	return vc->read(img) && !img.empty();
}


int BinocularCamera::isConnect() {
	qDebug() << "BinocularCamera::isConnect _isCameraInitialize " << _isCameraInitialize << _port;
	if (!_isCameraInitialize) {
		return DEV_ERR_IRI_CAMERA_NOT_INIT;
	}
	if (!_cam->isCameraConnected()) {

		_errorMsg = _cam->errorMsg;
		_errorCode = _cam->errorCode;

		return false;
	}
	return true;//success
}

bool BinocularCamera::read( cv::Mat& outMat) {

	if (_isCameraInitialize) {
		return _cam->vc->read(outMat);
	}
	return false;
}

void BinocularCamera::reOpen()
{

	close();
	open();
}

